// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'),
    imgUrl:'',
    showImg:'',
    headIcon: '../../assets/icons/按钮.png',
    err_active:false,
    right_active:false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  err_click(){
    let _this = this
    this.setData({
      err_active:!_this.data.err_active
    })
    setTimeout(() => {
      this.setData({
        err_active:!_this.data.err_active
      })
    }, 150);
    this.setData({
      ctx:null,
      imgUrl:''
    })
  },
  right_click(){
    let _this = this
    this.setData({
      right_active:!_this.data.right_active
    })
    setTimeout(() => {
      this.setData({
        right_active:!_this.data.right_active
      })
    }, 150);
    _this.creatIcon()
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    // console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  chooseImageTap(){
    var that = this;
    // that.data.imgUrl = ''
    wx.showActionSheet({
      itemList: ['从相册中选择'],
      itemColor: "#00000",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera')
          }
        }
      }
    })
  },
  chooseWxImage(type) {
    var that = this;
    var _this = this;
    var imgsPaths = that.data.imgs;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res.tempFilePaths[0]);
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success(res){
            console.log(res);
            _this.height = res.height
            _this.width = res.width
            console.log(_this.width, _this.height);

            if(_this.height>1080 || _this.width>1080){
              wx.showToast({
                title: '上传的图片太大, 请选择其他图片',
              })
              return;
            }
          }
        })
        that.setData({
          imgUrl:res.tempFilePaths[0]
        })
        that.creatCanvas()
      },
      fail:function(res){
        console.log(res);
        return
      }
    }) 
  },

  // 绘制头像
  creatCanvas(){
    console.log('执行');
    let _this = this;
    let ctx = wx.createCanvasContext('myCanvas', _this );
    _this.setData({
      ctx:ctx
    })
    // 绘制前查看图片的大小
    // const img = new Image()
    wx.getImageInfo({
      src: _this.data.imgUrl,
      success(res){
        _this.height = res.height
        _this.width = res.width
      }
    })
    var w = _this.width
    var h = _this.height
    var dw = 250/w          //canvas与图片的宽高比
    var dh = 250/h
    var ratio       
    // 裁剪图片中间部分
    if(w > 250 && h > 250 || w < 250 && h < 250){
        if (dw > dh) {
            ctx.drawImage(this.data.imgUrl, 0, (h - 250/dw)/2, w, 250/dw, 0, 0, 250, 250)
        } else {
            ctx.drawImage(this.data.imgUrl, (w - 250/dh)/2, 0, 250/dh, h, 0, 0, 250, 250)
        }
    }
    // 拉伸图片
    else{
        if(w < 250){
            ctx.drawImage(this.data.imgUrl, 0, (h - 250/dw)/2, w, 250/dw, 0, 0, 250, 250)
        }else {
            ctx.drawImage(this.data.imgUrl, (w - 250/dh)/2, 0, 250/dh, h, 0, 0, 250, 250)
        }
    }
    //drawImage 的参数查找官网
    // ctx.drawImage(this.data.imgUrl, 0, 0, 460, 460); //绘制上传的照片
    // ctx.drawImage(this.data.headIcon, 0, 0, 50, 50);//绘制添加的logo图片
    ctx.draw(true, () => {
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: (res) => {
          	//将绘制完成的图片赋值给变量
            // this.setData({
            //   showImg: res.tempFilePath,
            // })
            // this.saveImg()
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: '生成失败！',
              icon: "none"
            })
          },
        }, _this);
      }, 300);
    });
  },

  creatIcon(){
    
    let _this = this
    if(_this.data.imgUrl==='') {
      wx.showToast({
        title: '请添加图片',
      })
      return
    }
      let ctx= this.data.ctx
      ctx.drawImage(this.data.headIcon, 0, 0, 50, 50);
      ctx.draw(true, () => {
        setTimeout(() => {
          wx.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: (res) => {
              //将绘制完成的图片赋值给变量
              this.setData({
                showImg: res.tempFilePath,
              })
              console.log('showImg 成功');
              // this.saveImg()
            },
            fail: () => {
              wx.hideLoading();
              wx.showToast({
                title: '生成失败！',
                icon: "none"
              })
            },
          }, _this);
        }, 300);
      });
  },



 
  saveImg(){
    let that = this;
    console.log(that.data.showImg);
    if(that.data.showImg === '') {
      console.log('图片没有保留');
      return 
    }
    wx.saveImageToPhotosAlbum({
      filePath: that.data.showImg,
      success(data) {
        wx.showToast({
          title: "图片保存成功",
          icon: "success",
          mask: true
        })
      },

    })
  },

  //保存图片前判断是否拥有保存到相册权限
  getPhotosAlbumAuth() {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          _this.saveImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              _this.saveImg();
            },
            fail() {
              wx.showToast({
                title: '您没有授权，无法保存到相册',
                icon: 'none'
              })
            }
          })
        } else {
          wx.openSetting({
            success(result) {
              if (result.authSetting['scope.writePhotosAlbum']) {
                _this.saveImg();
              } else {
                uni.showToast({
                  title: '您没有授权，无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },
  
  onShareAppMessage(){}
})
